package com.demo.studentmanager.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.studentmanager.dto.SelectCourseListDto;
import com.demo.studentmanager.entity.Course;
import com.demo.studentmanager.entity.Score;
import com.demo.studentmanager.exception.BizException;
import com.demo.studentmanager.result.ResultCode;
import com.demo.studentmanager.service.IScoreService;
import com.demo.studentmanager.service.ISelectCourseService;
import com.demo.studentmanager.service.IStudentService;
import com.demo.studentmanager.util.CheckEntityUtil;
import com.demo.studentmanager.vo.SelectCourseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * @author ZHB
 */
@Api(tags = "选课模块")
@RequestMapping
@RestController
public class SelectCourseController {

    @Autowired
    private ISelectCourseService selectCourseService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IScoreService scoreService;

    @RequiresAuthentication
    @GetMapping("/selectCourse")
    @ApiOperation(value = "选课信息")
    public IPage<SelectCourseVO> getSelectCourse(@Validated SelectCourseListDto selectCourseListDto) {
        return selectCourseService.getSelectCourseList(selectCourseListDto);
    }

    @RequiresAuthentication
    @PutMapping("/selectCourse/{cno}/{sno}")
    @ApiOperation(value = "学生选课")
    public void upSelectCourse(@NotNull @PathVariable String cno, @NotNull @PathVariable String sno) {

        Course course = CheckEntityUtil.isNullById(cno, selectCourseService, ResultCode.COURSE_NOT_EXIST);
        course.setTotal(course.getTotal() + 1);

        CheckEntityUtil.isNullById(sno, studentService, ResultCode.STUDENT_NOT_EXIST);

        Score score = new Score().setSno(sno).setCno(cno);
        Wrapper<Score> queryWrapper = new QueryWrapper<>(score);
        if (scoreService.getOne(queryWrapper) != null) {
            throw new BizException(ResultCode.SC_EXIST);
        }

        //--待修改
        if ("已满".equals(course.getStatus())) {
            throw new BizException(ResultCode.COURSE_FULL);
        }
        if (course.getTotal().equals(course.getMaxSize())) {
            course.setStatus("已满");
            selectCourseService.updateById(course);
            throw new BizException(ResultCode.COURSE_FULL);
        }
        selectCourseService.updateById(course);
        scoreService.save(score);
    }
}
